import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:palette_generator/palette_generator.dart';

import '../common/extension/string_extension.dart';
import '../common/api_service.dart';
import '../common/images.dart';
import '../common/routes.dart';
import '../common/utils.dart';
import '../controllers/cartoon_app_bar_controller.dart';
import '../model/cartoon_model.dart';
import '../utils/utils.dart';
import '../widgets/cartoon_app_bar.dart';
import '../widgets/cartoon_banner_widget.dart';
import '../widgets/following_cartoon_item_view.dart';
import '../widgets/shadow_text.dart';
import '../widgets/swiper_custom_rect_pagination_builder.dart';

class CartoonsPage extends StatefulWidget {
  const CartoonsPage({super.key});

  @override
  State<CartoonsPage> createState() => _CartoonsPageState();
}

class _CartoonsPageState extends State<CartoonsPage> {
  final _pageController = PageController();
  late final String _tabId;
  int _page = 1;
  final List<CartoonModel> _cartoonList = [];
  final List<CartoonModel> _rcmdCartoonList = [];
  bool _isLoading = false;
  int _itemIndex = 0;

  @override
  void initState() {
    super.initState();

    _pageController.addListener(() {});

    _getRecommendCartoons();
  }

  void _loadMoreData() {
    _getCartoonList(isRefresh: false);
  }

  void _getRecommendCartoons() {
    ApiService().getRecommendCartoons((list) {
      _rcmdCartoonList.clear();
      _rcmdCartoonList.addAll(list);
      _getCartoonTabId();

      if (_rcmdCartoonList.length >= 3) {
        List<String> urls = [];
        _rcmdCartoonList.take(3).forEach((item) {
          urls.add(item.avatar);
        });
        final controller = Get.find<CartoonAppBarController>();
        controller.initialize(urls);
      }
    }, () {
      _getCartoonTabId();
    });
  }

  void _getCartoonTabId() {
    ApiService().getCartoonTabId((id) {
      _tabId = id;
      _getCartoonList();
    }, () {});
  }

  void _getCartoonList({bool isRefresh = true}) {
    _isLoading = true;
    ApiService().getCartoonList(_tabId, _page, (list) {
      if (list.length > 0) {
        _page++;
      }
      setState(() {
        _isLoading = false;
        if (isRefresh) {
          _cartoonList.clear();
        }
        _cartoonList.addAll(list);
      });
    }, () {});
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        surfaceTintColor: Colors.white,
        title: const CartoonAppBar(),
      ),
      body: PageView.builder(
        scrollDirection: Axis.vertical,
        controller: _pageController,
        itemCount: _cartoonList.length,
        onPageChanged: (index) {
          if (_itemIndex < index) {
            print("⬆向上滚动 index=$index");
            if (index == 1) {
              final controller = Get.find<CartoonAppBarController>();
              controller.startAnimationSequence(reset: true);
            }
            if (index == _cartoonList.length - 2 && !_isLoading) {
              print("加载更多数据~");
              _loadMoreData();
            }
          } else {
            print("⬇向下滚动 index=$index");
            if (index == 0) {
              final controller = Get.find<CartoonAppBarController>();
              controller.startAnimationSequence(reset: false);
            }
          }
          setState(() {
            _itemIndex = index;
          });
        },
        itemBuilder: (context, index) {
          final cartoon = _cartoonList[index];
          if (index == 0) {
            return Column(
              children: [FollowCartoon(rcmdCartoonList: _rcmdCartoonList), Expanded(child: CartoonCardWidget(cartoonModel: cartoon))],
            );
          } else {
            return CartoonCardWidget(cartoonModel: cartoon);
          }
        },
      ),
    );
  }
}

class FollowCartoon extends StatefulWidget {
  final List<CartoonModel> rcmdCartoonList;

  const FollowCartoon({super.key, required this.rcmdCartoonList});

  @override
  State<FollowCartoon> createState() => _FollowCartoonState();
}

class _FollowCartoonState extends State<FollowCartoon> {
  @override
  Widget build(BuildContext context) {
    final count = widget.rcmdCartoonList.length;
    return Stack(
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 6, 16, 0),
          child: Row(
            children: [
              const Expanded(
                child: Text("我的关注", style: TextStyle(color: Colors.black45)),
              ),
              InkWell(
                  child: const Text("所有关注>", style: TextStyle(color: Colors.black45)),
                  onTap: () {
                    Get.toNamed(Routes.FOLLOWING);
                  })
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.fromLTRB(16, 36, 0, 0),
          height: 85,
          child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: count,
              itemBuilder: (context, index) {
                final cartoon = widget.rcmdCartoonList[index];
                return FollowingCartoonItemView(cartoon: cartoon);
              }),
        ),
      ],
    );
  }
}

class CartoonCardWidget extends StatefulWidget {
  final CartoonModel cartoonModel;

  const CartoonCardWidget({super.key, required this.cartoonModel});

  @override
  State<CartoonCardWidget> createState() => _CartoonCardWidgetState();
}

class _CartoonCardWidgetState extends State<CartoonCardWidget> {
  Color? _dominantColor;

  @override
  void initState() {
    super.initState();
    _updatePalette();
  }

  Future<void> _updatePalette() async {
    var imageUrl = widget.cartoonModel.avatar;
    if (widget.cartoonModel.banner != null && widget.cartoonModel.banner != "") {
      imageUrl = widget.cartoonModel.banner ?? "";
    }
    imageUrl = imageUrl.getThumbUrl(size: 50);
    final PaletteGenerator paletteGenerator = await PaletteGenerator.fromImageProvider(
      CachedNetworkImageProvider(imageUrl),
    );

    if (!mounted) return;

    setState(() {
      _dominantColor = paletteGenerator.dominantColor?.color;
    });
  }

  @override
  Widget build(BuildContext context) {
    final cartoon = widget.cartoonModel;
    final useNum = Utils.formatNumber(cartoon.useNum ?? 0);
    final fansNum = Utils.formatNumber(cartoon.fansNum ?? 0);
    final tplNum = Utils.formatNumber(cartoon.tplNum ?? 0);

    var imageUrl = widget.cartoonModel.avatar;
    if (widget.cartoonModel.banner != null && widget.cartoonModel.banner != "") {
      imageUrl = widget.cartoonModel.banner ?? "";
    }

    return GestureDetector(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12.0),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withAlpha(25),
                spreadRadius: 2,
                blurRadius: 5,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Stack(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(12.0),
                child: Stack(
                  children: [
                    CachedNetworkImage(
                      fit: BoxFit.cover,
                      fadeInDuration: const Duration(milliseconds: 100),
                      fadeOutDuration: const Duration(seconds: 0),
                      imageUrl: imageUrl,
                      width: double.infinity,
                      height: double.infinity,
                      placeholder: (context, url) {
                        return Container(
                          color: Colors.grey[50],
                          child: const Center(
                            child: Text(
                              "FlowGPT",
                              style: TextStyle(color: Colors.white, fontSize: 24, fontStyle: FontStyle.italic, shadows: [Shadow(color: Colors.black12, blurRadius: 1, offset: Offset(1.0, 1.0))]),
                            ),
                          ),
                        );
                      },
                    ),
                    Align(
                      alignment: Alignment.bottomCenter,
                      child: FractionallySizedBox(
                        widthFactor: 1,
                        heightFactor: 0.7, // Container height is 50% of the CachedNetworkImage height
                        child: Container(
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                            colors: [_dominantColor ?? Colors.black87, Colors.transparent], // 渐变颜色
                            begin: Alignment.bottomCenter,
                            end: Alignment.topCenter,
                          )),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Row(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.white, width: 2),
                            borderRadius: BorderRadius.circular(22),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(20),
                            child: CachedNetworkImage(
                              height: 40,
                              width: 40,
                              fadeInDuration: const Duration(seconds: 0),
                              fadeOutDuration: const Duration(seconds: 0),
                              fit: BoxFit.cover,
                              imageUrl: cartoon.avatar,
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ShadowedText(
                              cartoon.name,
                              style: const TextStyle(color: Colors.white, fontSize: 18),
                            ),
                            ShadowedText(
                              "@${cartoon.user!.nickname} 创作",
                              style: const TextStyle(color: Colors.white70, fontSize: 13),
                            )
                          ],
                        )
                      ],
                    ),
                    if (!isEmpty(cartoon.summary)) const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      child: ShadowedText(
                        cartoon.summary,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        softWrap: true,
                        style: TextStyle(color: Colors.white.withAlpha(215), fontSize: 15),
                      ),
                    ),
                    SizedBox(height: cartoon.summary.isNotEmpty ? 10 : 0),
                    Row(
                      children: [
                        Column(
                          children: [
                            ShadowedText(useNum, style: const TextStyle(fontFamily: 'OpenSans', color: Colors.white, fontSize: 20)),
                            const ShadowedText("总互动", style: TextStyle(color: Colors.white60, fontSize: 13)),
                          ],
                        ),
                        const SizedBox(width: 10),
                        Column(
                          children: [
                            ShadowedText(fansNum, style: const TextStyle(fontFamily: 'OpenSans', color: Colors.white, fontSize: 20)),
                            const ShadowedText("粉丝", style: TextStyle(color: Colors.white60, fontSize: 13)),
                          ],
                        ),
                        const SizedBox(width: 10),
                        Column(
                          children: [
                            ShadowedText(tplNum, style: const TextStyle(fontFamily: 'OpenSans', color: Colors.white, fontSize: 20)),
                            const ShadowedText("内容", style: TextStyle(color: Colors.white60, fontSize: 13)),
                          ],
                        ),
                        Spacer(),
                        Image.asset(Images.cartoonlist_enter, width: 68, height: 40, fit: BoxFit.cover)
                      ],
                    ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      height: 130,
                      child: Swiper(
                        itemBuilder: (BuildContext context, int index) {
                          var pipe = cartoon.pipeList?[index];
                          return CartoonBannerWidget(pipe: pipe!);
                        },
                        autoplay: true,
                        itemCount: cartoon.pipeList!.length,
                        pagination: (cartoon.pipeList!.length > 1
                            ? const SwiperPagination(
                                builder: SwiperCustomRectPaginationBuilder(
                                  color: Colors.white54,
                                  activeColor: Colors.white,
                                  size: Size(20, 2),
                                  activeSize: Size(20, 2),
                                ),
                                margin: EdgeInsets.symmetric(vertical: 3))
                            : null),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
      onTap: () {
        Get.toNamed(Routes.CARTOON_INFO, arguments: {"cartoonId": cartoon.id});
      },
    );
  }
}
